import { fileURLToPath, URL } from 'node:url'
import autoprefixer from 'autoprefixer'
import { defineConfig, loadEnv } from 'vite'
import { createVitePlugins } from './build/plugins.js'

export default defineConfig(({ mode }) => {
  const config = loadEnv(mode, process.cwd(), '')
  return {
    define: {
      __VUE_OPTIONS_API__: false,
    },
    css: {
      postcss: {
        plugins: [
          autoprefixer({
            overrideBrowserslist: [
              'Chrome > 86',
              'ff > 31',
              'last 2 versions',
            ],
            grid: true,
          }),
        ],
      },
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler',
          additionalData: `@use "@/assets/css/mixin.scss" as *;`,
        },
      },
    },
    plugins: createVitePlugins(config),
    server: {
      port: 8080,
      open: true,
      host: true,
      proxy: {
        // 不知道部署环境 先全部用代理
        [config.VITE_URL_PREFIX]: {
          target: config.VITE_REQUEST_URL,
          changeOrigin: true,
          rewrite: (path) => {
            return path.replace(new RegExp(`^${config.VITE_URL_PREFIX}`), '')
          },
        },
      },
    },
    build: {
      target: 'esnext',
      minify: 'esbuild',
      chunkSizeWarningLimit: 1500,
      reportCompressedSize: false,
      rollupOptions: {
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        },
      },
      esbuild: {
        drop: ['console', 'debugger'],
      },
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        'components': fileURLToPath(new URL('./src/components', import.meta.url)),
        'assets': fileURLToPath(new URL('./src/assets', import.meta.url)),
      },
    },
  }
})
